import { getNews } from "./api";
import { Dialog } from "vant";
import { Tip } from "@/utils";
// environment 测试环境是2 生产环境是1
let environment = 1;
Dialog.setDefaultOptions({
  confirmButtonColor: "#006BE0",
  closeOnPopstate: false,
});
//检测新版本升级
export function upgradeForAndroid() {
  //从window中获取Cordova对象
  var cordova = window.cordova;
  //apk所在的服务器路径（下载路径）
  // 获取apk在服务器上所在的地址

  var url = `${process.env.VUE_APP_APPVERSION_BASE_URL}/apkHistory/download?code=${process.env.VUE_APP_APPVERSION_CODE}&environment=${environment}`;
  url = encodeURI(url);

  var targetPath =
    cordova.file.externalCacheDirectory +
    `${process.env.VUE_APP_APPVERSION_CODE}.apk`;
  downLoadApp();
  function downLoadApp() {
    // 初始化FileTransfer对象
    // eslint-disable-next-line no-undef
    var fileTransfer = new FileTransfer();
    fileTransfer.onprogress = function(progressEvent) {
      if (progressEvent.lengthComputable) {
        var downloadProgress =
          (progressEvent.loaded / progressEvent.total) * 100;
        var result = "已下载：" + Math.floor(downloadProgress) + "%";

        if (Math.floor(downloadProgress) == 100) {
          Dialog.alert({
            title: result,
            message: "下载完成后会自动弹出安装",
            showConfirmButton: false,
            showCancelButton: true,
          })
            .then()
            .catch(() => {
              navigator.app.exitApp();
            });
        } else {
          Dialog.alert({
            title: result,
            message: "下载完成后会自动弹出安装",
            showConfirmButton: false,
            showCancelButton: false,
          });
        }
      }
    };
    // 调用download方法
    fileTransfer.download(
      url, //uri网络下载路径
      targetPath, //url本地存储路径
      function(entry) {
        console.log("download complete: " + entry.toURL());
        cordova.plugins.fileOpener2.open(
          targetPath,
          "application/vnd.android.package-archive",
          {
            error: function(e) {
              Dialog.alert({
                title: "打开下载文件失败",
                message: "请退出后重新进入应用",
              }).then((res) => {
                navigator.app.exitApp();
              });
            },
            success: function() {
              console.log("open successfully");
            },
          }
        );
      },
      function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
      },
      true
    );
  }
}
/*
 * 检测升级方法
 */
export const checkUpgrade = async (locationVersion) => {
  /**
   * 从服务器获取应用的版本信息，和本地应用版本对比
   */
  let params = {
    code: process.env.VUE_APP_APPVERSION_CODE,
    environment: environment,
  };
  let response = await getNews({
    params,
  });
  var serverVersion = response.result.versionCode;
  if (locationVersion != serverVersion) {
    Dialog.confirm({
      title: "发现版本: " + serverVersion + ",请进行升级",
      message: "建议您在WIFI环境下升级",
    })
      .then(() => {
        upgradeForAndroid();
      })
      .catch(() => {
        navigator.app.exitApp();
      });
  }
  // 监听网络状况，无网络时
  document.addEventListener(
    "offline",
    function() {
      console.log("网络异常，不能连接到服务器！");
      Dialog.alert({
        title: "网络异常，不能连接到服务器！",
        message: "请在连接网络的情况下升级应用",
      }).then(() => {
        navigator.app.exitApp();
      });
    },
    false
  );
};
